<?php

namespace app\admin\model\yunfood;

use think\Exception;

/**
 * 菜品分类
 */
class FoodCategory extends \addons\yunfood\model\FoodCategory
{
    // 自定义初始化
    protected static function init()
    {
        self::beforeWrite(function ($record) {
            $scenario = $record->data['scenario'] ?? null;
            if ($scenario) {
                unset($record->data['scenario']);  // 避免afterInsert的操作
            }

            if (! empty($record->data['deleted_at'])) {
                if (Food::where(['category_id' => $record->id])->count() > 0) {
                    throw new Exception('"' . $record['name'] . '"分类下存在菜品，不支持删除');
                }
            }

            return true;
        });

        self::afterInsert(function ($row) {
            $row->save(['weigh' => $row['id']]);
        });
    }
}
